package controllers

import (
	"day12z/models"
	beego "github.com/beego/beego/v2/server/web"
)

type WWW struct {
	beego.Controller
}

type Msg struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Date interface{} `json:"date"`
}

func (w *WWW) Add() {
	boa := w.GetString("boa")
	nie := w.GetString("nie")
	times := w.GetString("times")
	zuo := w.GetString("zuo")
	ww := models.Books{
		Boa:   boa,
		Nie:   nie,
		Times: times,
		Zuo:   zuo,
	}
	err := models.DB.Create(&ww).Error
	if err != nil {
		w.Data["json"] = Msg{
			Code: 0,
			Msg:  "添加失败",
			Date: nil,
		}
		w.ServeJSON()
		return
	} else {
		w.Data["json"] = Msg{
			Code: 200,
			Msg:  "添加成功",
			Date: ww,
		}
		w.ServeJSON()
	}
}

func (w *WWW) List() {
	page, _ := w.GetInt("page", 1)
	size, _ := w.GetInt("size", 3)
	offset := (page - 1) * size
	var count int64
	var qwe []models.Books
	models.DB.Model(models.Books{}).Count(&count)
	err := models.DB.Offset(offset).Limit(size).Find(&qwe).Error
	if err != nil {
		w.Data["json"] = Msg{
			Code: 0,
			Msg:  "分页失败",
			Date: nil,
		}
		w.ServeJSON()
		return
	} else {
		pageDate := make(map[string]interface{})
		pageDate["qwe"] = qwe
		pageDate["count"] = count
		w.Data["json"] = Msg{
			Code: 200,
			Msg:  "分页成功",
			Date: pageDate,
		}
		w.ServeJSON()
	}
}
